package cn.yhp.gateway.session;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**
 * 网关会话服务
 * @author yhp
 * @description
 * @date 2024/5/6
 */
public class SessionServer implements Callable<Channel> {

    private final Logger logger= LoggerFactory.getLogger(SessionServer.class);

    private final EventLoopGroup boss=new NioEventLoopGroup(1);
    private final EventLoopGroup work=new NioEventLoopGroup();

    private Channel channel;

    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture=null;
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss,work)
                    // 设置非阻塞，用他来建立新accept连接
                    .channel(NioServerSocketChannel.class)
                    // 临时存在已完成三次握手的请求的队列最大长度，如果大于次长度，请求将被拒绝，不设置默认50
                    .option(ChannelOption.SO_BACKLOG,128)
                    // 初始化管道
                    .childHandler(new SessionChannelInitializer());
            channelFuture=bootstrap.bind(new InetSocketAddress(8886)).syncUninterruptibly();
            this.channel=channelFuture.channel();
        }catch (Exception e){
            logger.error("socket服务端启动失败",e);
        }finally {
            if (channelFuture!=null && channelFuture.isSuccess()){
                logger.info("socket服务端启动成功...");
            }else {
                logger.error("socket服务端启动失败!");
            }
        }
        return channel;
    }
}
